package com.modular.exception;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class ModularException extends RuntimeException {
    private String code;
    private String errMsg;
    private Object[] params;

    public ModularException(String errMsg){
        this.errMsg = errMsg;
    }

    public ModularException(String code, String errMsg){
        this.code = code;
        this.errMsg = errMsg;
    }

    public ModularException(String code, String errMsg, Object ...params){
        this.code = code;
        this.errMsg = errMsg;
        this.params = params;
        formatErrMsg();
    }

    public ModularException(String code, String errMsg, Throwable e){
        super(e);
        this.code = code;
        this.errMsg = errMsg;

    }

    public ModularException(String code, String errMsg, Throwable e, Object ...params){
        super(e);
        this.code = code;
        this.errMsg = errMsg;
        this.params = params;
        formatErrMsg();
    }

    public ModularException(CodeDesc codeDesc){
        this.code = codeDesc.getCode();
        this.errMsg = codeDesc.getErrMsg();
    }

    public ModularException(CodeDesc codeDesc, Throwable e){
        this(codeDesc.getCode(),codeDesc.getErrMsg(),e);
    }
    public ModularException(CodeDesc codeDesc, Object ...params){
        this(codeDesc.getCode(),codeDesc.getErrMsg(),params);
    }
    public ModularException(CodeDesc codeDesc, Throwable e, Object ...params){
        this(codeDesc.getCode(),codeDesc.getErrMsg(),e,params);
    }

    private void formatErrMsg(){
        if(ObjectUtil.isNull(params)){
            return;
        }
        if(params.length <= 0){
            return;
        }
        this.errMsg = StrUtil.format(this.errMsg,params);
    }

}
